package com.ypan.mail.common.interceptor;

import com.ypan.mail.common.annotation.PassToken;
import com.ypan.mail.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author ypan
 * @Date on 2021/4/19  17:45
 * @Desc
 */
@Slf4j
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    @Value("${jwt.uname}")
    private String uname;

    @Value("${jwt.pwd}")
    private String pwd;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        response.setContentType("text/plain; charset=utf-8");
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //默认全部检查
        else {
            log.info("被jwt拦截需要验证");
            // 执行认证
            if (token == null) {
                //这里其实是登录失效,没token了   这个错误也是我自定义的，读者需要自己修改
                response.getWriter().println("登录失效！");
                return false;
            }

            // 获取 token 中的 user Name
            String loginUname = JwtUtils.getAudience(token);

            //找找看是否有这个user   因为我们需要检查用户是否存在，读者可以自行修改逻辑
            if(!uname.equals(loginUname)){
                response.getWriter().println("用户不存在！");
                return false;
            }

            // 验证 token
            JwtUtils.verifyToken(token, loginUname);

            //获取载荷内容
            String pwd = JwtUtils.getClaimByName(token, "pwd").asString();

            //放入attribute以便后面调用
            request.setAttribute("pwd", pwd);


            return true;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
